package com.itheima.service.impl;

import com.itheima.service.BaiDuWeatherService;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class BaiDuWeatherImpl implements BaiDuWeatherService {

    private static final String URL = "https://api.map.baidu.com/weather/v1/?";
    private static final String AK = "uUfEF5LivVnhaj7Ajq4hTJmfO1vOF1XT"; // 替换为你的实际 API 密钥

    @Override
    public String getWeather() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("district_id", "330603"); // 绍兴柯桥区的行政区划代码
        params.put("data_type", "all");
        params.put("ak", AK);

        try {
            return requestGetAK(URL, params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送 GET 请求获取天气数据
     * @param strUrl 请求的 URL
     * @param param 请求参数
     * @return 返回的 JSON 数据
     * @throws Exception 异常
     */
    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuilder queryString = new StringBuilder();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey()).append("=");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8")).append("&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        URL url = new URL(queryString.toString());
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();

        return buffer.toString();
    }
}